<?php
namespace User\Controller;

class AvatarController extends MainController {

    public function index(){
      	$this->display();
    }

    public function save(){
        $path = '.'.C('UPLOAD_PATH').'avatar/';
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = C('image_size')*1000;  //是指上传文件的大小，默认为-1,不限制上传文件大小bytes
        $upload->rootPath = $path;        //上传保存到什么地方？路径建议大家已主文件平级目录或者平级目录的子目录来保存
        $upload->autoSub = true;
        $upload->subType = 'date';
        $upload->dateFormat = 'Ym';
        $upload->saveRule=uniqid;    //上传文件的文件名保存规则  time uniqid  com_create_guid  uniqid
        $upload->uploadReplace=true;     //如果存在同名文件是否进行覆盖
        $upload->allowExts= explode(',',C('image_exts'));     //准许上传的文件后缀
        $info = $upload->upload();

        if($info){
            foreach($info as $file){
                if (empty($dir)) {
                    $url = $file['savepath'].$file['savename'];
                }else{
                    $url = $dir.'/'.$file['savepath'].$file['savename'];
                }
            } 

            //缩放处理    
            $tempUrl = C('UPLOAD_PATH').'avatar/'.$url;
            $tempUrl = substr($tempUrl,1,strlen($tempUrl));
            $im=getimagesize($tempUrl);
            if ($im[0]>600) {
                import("Common.ORG.Thumb");
                $resizeimage = new \Thumb($tempUrl,600,1,$tempUrl,-1,0);  //生成宽度660
            }   

            //保存照片
            $map['userid'] = $this->userID;     
            M('Mentees')->where($map)->setField('face',C('UPLOAD_PATH').'avatar/'.$url);        

            echo json_encode(array(
                'url' => $url,   //保存后的文件路径
                'state'    => 'SUCCESS'  //上传状态，成功时返回SUCCESS,其他任何值将原样返回至图片上传框中
            ));
            
        }else{
            //是专门来获取上传的错误信息的            
            echo json_encode(array(
                'state' => $upload->getError(),  //上传状态，返回错误结果
            ));
        }
    }


}